import { ModernBaseService } from '../service/base/ModernBaseService';
import { Item } from '../shared/face';
import { ItemType, quality } from '../shared/face/enums';
import { EquipService } from '../service/EquipService';

/**
 * 道具数据访问层
 * 职责：
 * 1. 道具数据的持久化
 * 2. 道具查询和更新操作
 * 3. 数据缓存管理
 * 4. 数据验证和转换
 */
export class PropRepository extends ModernBaseService {
    private propCache = new Map<string, CachedPropData>();
    private readonly CACHE_TTL = 300000; // 5分钟缓存

    /**
     * 获取道具配置数据
     * @param type 道具类型
     * @param id 道具ID
     * @returns 道具配置
     */
    async getPropConfig(type: ItemType, id: string): Promise<any> {
        return this.cachedFetch(`prop_config_${type}_${id}`, async () => {
            this.validateRequiredParams({ type, id }, ['type', 'id']);

            let config: any;
            switch (type) {
                case ItemType.道具:
                    config = this.config.get(this.configKey.道具表)?.get(id);
                    break;
                case ItemType.资源:
                    config = this.config.get(this.configKey.资源表)?.get(id);
                    break;
                case ItemType.消耗品:
                    config = this.config.get(this.configKey.消耗品表)?.get(id);
                    break;
                default:
                    throw new Error(`未知的道具类型: ${type}`);
            }

            if (!config) {
                throw new Error(`道具配置不存在: ${type}-${id}`);
            }

            return config;
        }, this.CACHE_TTL);
    }

    /**
     * 获取装备模板配置
     * @param id 装备模板ID
     * @returns 装备模板配置
     */
    async getEquipTemplate(id: string): Promise<any> {
        return this.cachedFetch(`equip_template_${id}`, async () => {
            this.validateRequiredParams({ id }, ['id']);

            // 通过DI获取 EquipService，消除对静态 EquipManage 的直接依赖
            const equipService = this.getService<EquipService>('EquipService');
            const template = equipService.getTemplateById(id);
            
            if (!template) {
                throw new Error(`装备模板不存在: ${id}`);
            }

            return template;
        }, this.CACHE_TTL);
    }

    /**
     * 获取随机装备模板ID
     * @returns 随机装备模板ID
     */
    async getRandomEquipTemplateId(): Promise<string> {
        return this.cachedFetch('random_equip_template_id', async () => {
            const equipService = this.getService<EquipService>('EquipService');
            return equipService.getRandomTemplateId();
        }, this.CACHE_TTL);
    }

    /**
     * 获取装备属性配置
     * @param sys 系统
     * @param type 类型
     * @param job 职业
     * @param soltType 槽位类型
     * @returns 装备属性配置列表
     */
    async getEquipAttributeConfig(sys: string, type: string, job: string, soltType: string): Promise<any[]> {
        return this.cachedFetch(`equip_attr_${sys}_${type}_${job}_${soltType}`, async () => {
            this.validateRequiredParams({ sys, type, job, soltType }, ['sys', 'type', 'job', 'soltType']);

            const config = this.config.get(this.configKey.配置_装备属性) as Map<string, any>;
            if (!config) {
                return [];
            }

            return Array.from(config.values())
                .filter(item => item.sys === sys && item.type === type && item.job === job && item.solt === soltType);
        }, this.CACHE_TTL);
    }

    /**
     * 获取击杀奖励配置
     * @param policy 策略名称
     * @returns 击杀奖励配置
     */
    async getKillRewardConfig(policy: string): Promise<any> {
        return this.cachedFetch(`kill_reward_${policy}`, async () => {
            this.validateRequiredParams({ policy }, ['policy']);

            const config = this.config.get(`${this.configKey.通用击杀奖励}_通用击杀`) as Map<string, any>;
            if (!config) {
                throw new Error(`击杀奖励配置不存在: ${policy}`);
            }

            const configItem = config.get(policy);
            if (!configItem) {
                throw new Error(`击杀奖励策略不存在: ${policy}`);
            }

            return configItem;
        }, this.CACHE_TTL);
    }

    /**
     * 获取血统配置
     * @param id 血统ID
     * @returns 血统配置
     */
    async getTalentConfig(id: string): Promise<any> {
        return this.cachedFetch(`talent_${id}`, async () => {
            this.validateRequiredParams({ id }, ['id']);

            const config = this.config.get(this.configKey.配置_血统)?.get(id);
            if (!config) {
                throw new Error(`血统配置不存在: ${id}`);
            }

            return config;
        }, this.CACHE_TTL);
    }

    /**
     * 保存道具数据
     * @param item 道具数据
     */
    async saveProp(item: Item): Promise<void> {
        await this.safeExecute(async () => {
            this.validateRequiredParams({ item }, ['item']);

            // 这里可以添加道具数据的持久化逻辑
            // 目前主要是缓存更新
            this.updateCache(`prop_${item.id}`, {
                data: item,
                timestamp: Date.now()
            });

            this.log(`Prop data saved: ${item.id}`);
        }, 'saveProp');
    }

    /**
     * 批量保存道具数据
     * @param items 道具数据列表
     */
    async saveProps(items: Item[]): Promise<void> {
        await this.safeExecute(async () => {
            this.validateRequiredParams({ items }, ['items']);

            for (const item of items) {
                await this.saveProp(item);
            }

            this.log(`Batch saved ${items.length} props`);
        }, 'batchSaveProps');
    }

    /**
     * 清除过期缓存
     */
    private clearExpiredCache(): void {
        const now = Date.now();
        for (const [key, cached] of this.propCache.entries()) {
            if (now - cached.timestamp > this.CACHE_TTL) {
                this.propCache.delete(key);
            }
        }
    }

    /**
     * 更新缓存
     * @param key 缓存键
     * @param data 缓存数据
     */
    private updateCache(key: string, data: CachedPropData): void {
        this.propCache.set(key, data);
        this.clearExpiredCache();
    }

    /**
     * 获取缓存数据
     * @param key 缓存键
     * @returns 缓存数据或null
     */
    private getCachedData(key: string): CachedPropData | null {
        const cached = this.propCache.get(key);
        if (!cached) return null;

        if (Date.now() - cached.timestamp > this.CACHE_TTL) {
            this.propCache.delete(key);
            return null;
        }

        return cached;
    }

    /**
     * 带缓存的异步操作
     * @param key 缓存键
     * @param operation 异步操作
     * @param ttl 缓存时间
     * @returns 操作结果
     */
    private async cachedFetch<T>(key: string, operation: () => Promise<T>, ttl: number): Promise<T> {
        const cached = this.getCachedData(key);
        if (cached) {
            return cached.data as T;
        }

        const result = await operation();
        this.updateCache(key, {
            data: result,
            timestamp: Date.now()
        });

        return result;
    }
}

/**
 * 缓存的道具数据
 */
interface CachedPropData {
    data: any;
    timestamp: number;
}


